import { getAction } from '@/api/manage';
import { ajaxGetDictItems,getDictItemsFromCache } from '@/api/api';
import { USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"
export const productMixins = {
  data(){
    return {
      treeData: [],
      queryParam: {},
      ipagination:{
        current: 1,
        pageSize: 20
      },
      replaceFields: {
        key: 'id',
        title: 'name',
        children: 'children',
        value: 'id',
      },
      url: {
        list_: '/hzkj-product/product/productLibrary/category/rootList',
        childList: "/hzkj-product/product/productLibrary/category/childList",
        queryMyCategory: "/hzkj-product/product/productLibrary/category/queryMyCategory"
      }
    }
  },
  methods: {
    loadData_(arg, type, categoryId, flag = false) {
      return new Promise(async (resolve, reject) => {
        this.treeData = [];
        if(type === 'queryMyCategory'){
          // 获取自己权限下的数据
          let treeData = await this.queryMyCategory(categoryId, flag);
          resolve(treeData);
          return;
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        var params = {
          pageNo: this.ipagination.current,
          pageSize: this.ipagination.pageSize,
          ...this.queryParam
        }
        getAction(this.url.list_, params).then(async (res) => {
          if (res.success) {
            let treeData = (res.result && res.result.records) || [];
            await Promise.all(treeData.map(async item => {
              // return无效,直接使用赋值
              if(item.hasChild && item.hasChild === '1'){
                item.children = await this.getchildList(item, flag);
              }
            }))
            // 处理assignerList
            this.treeData = treeData;
            resolve(this.treeData);
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.loading = false;
        })
      })
    },
    getchildList(item, flag){
      return new Promise((resolove, reject) => {
        getAction(this.url.childList, { pid: item.id }).then(async (res) => {
          if(res.success){
            let records = (res.result && res.result.records) || [];
            await Promise.all(records.map(async item => {
              // return无效,直接使用赋值
              if(item.hasChild && item.hasChild === '1'){
                item.children = await this.getchildList(item, flag);
              }
              item.disabled = flag ? true : false;
            }))
            resolove(records);
          }else{
            this.$message.warning(res.message);
          }
        })
      })
    },
    filterTreeNode(inputValue, treeNode){
      try{
        return treeNode && treeNode.data && treeNode.data.props && treeNode.data.props.title && treeNode.data.props.title.indexOf(inputValue) > -1;
      }catch(e){}
    },
    handleTreeData(treeData, flag){
      return treeData = treeData.map(item => {
        return {
          ...item,
          children: (item.children && item.children.length) ? this.handleTreeData(item.children, flag) : null,
          disabled: flag ? true : false
        }
      })
    },
    handleTreeData_(treeData, categoryId, flag){
      return treeData = treeData.map(item => {
        let curItem = {
          ...item,
          children: (item.children && item.children.length) ? this.handleTreeData_(item.children, categoryId, flag) : null,
          disabled: (flag || (item.isDeleted && item.id != categoryId)) ? true : false
        }
        if(!(curItem.children && curItem.children.length)){
          delete curItem.children;
        }
        return curItem;
      })
    },
    queryMyCategory(categoryId, flag){
      return new Promise((resolve, reject) => {
        getAction(this.url.queryMyCategory, { includeIds: categoryId }).then((res) => {
          if(res.success){
            let treeData = res.result || [];
            this.treeData = this.handleTreeData_(treeData, categoryId, flag);
            resolve(this.treeData);
          }else{
            this.$message.warning(res.message);
          }
        })
      })
    },
    getColor(record){
      // 1: 黑名单，2：白名单，3：灰名单， 4：正常，5：核心
      if(record.supplierStatus === 1){
        return '#f5222d';
      }else if(record.supplierStatus === 2){
        return '#d3d3d3';
      }else if(record.supplierStatus === 3){
        return '#a9a9a9';
      }else if(record.supplierStatus === 4){
        return '#18a05e';
      }else if(record.supplierStatus === 5){
        return '#40a9ff';
      }
    },
    initDictData(dictCode){
      return new Promise((resolve, reject) => {
        if (getDictItemsFromCache(dictCode)) {
          let customOptions = getDictItemsFromCache(dictCode);
          resolve(customOptions);
        }else{
          ajaxGetDictItems(dictCode, null).then((res) => {
            if (res.success) {
              let customOptions = res.result;
              resolve(customOptions);
            }
          })
        }
      })
    },
    filterGlobalPermission( value ) {
      //console.log("全局页面权限--Global--");
    
      let permissionList = [];
      let allPermissionList = [];
    
      //let authList = Vue.ls.get(USER_AUTH);
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
      for (let auth of authList) {
        if(auth.type != '2') {
          permissionList.push(auth);
        }
      }
      //console.log("页面权限--Global--",sessionStorage.getItem(SYS_BUTTON_AUTH));
      let allAuthList = JSON.parse(sessionStorage.getItem(SYS_BUTTON_AUTH) || "[]");
      for (let gauth of allAuthList) {
        if(gauth.type != '2') {
          allPermissionList.push(gauth);
        }
      }
      //设置全局配置是否有命中
      let invalidFlag = false;//无效命中
      if(allPermissionList != null && allPermissionList != "" && allPermissionList != undefined && allPermissionList.length > 0){
        for (let itemG of allPermissionList) {
          if(value === itemG.action){
            if(itemG.status == '0'){
              invalidFlag = true;
              break;
            }
          }
        }
      }
      if(invalidFlag){
        return false;
      }
      if (permissionList === null || permissionList === "" || permissionList === undefined||permissionList.length<=0) {
        return false;
      }
      let permissions = [];
      for (let item of permissionList) {
        //权限策略1显示2禁用
        if(item.type != '2'){
          //update--begin--autor:wangshuai-----date:20200729------for：按钮权限，授权标识的提示信息是多个用逗号分隔逻辑处理 gitee#I1OUGU-------
          if(item.action){
            if(item.action.includes(",")){
              let split = item.action.split(",")
                for (let i = 0; i <split.length ; i++) {
                  if(!split[i] ||split[i].length==0){
                    continue;
                  }
                  permissions.push(split[i]);
              }
            }else{
              permissions.push(item.action);
            }
          }
          //update--end--autor:wangshuai-----date:20200729------for：按钮权限，授权标识的提示信息是多个用逗号分隔逻辑处理 gitee#I1OUGU------
        }
      }
      if (!permissions.includes(value)) {
        return false;
      }
      return true;
    }
  }
}